'use strict';

(function () {
    // 特别注意，浏览器缩放必须100%，改了会对齐不了

    var g_allData = [],
        g_areaArr = [],
        g_dateArr = [];
    var g_rowHeight = 30;
    var g_sizeWidth = 10; // 每1个图形size占的宽度，和css文件要同步修改

    // 画图
    var draw = function draw(p_allData, p_areaArr, p_dateArr) {
        g_allData = p_allData;
        g_areaArr = p_areaArr;
        g_dateArr = p_dateArr;

        drawBanner();
        drawFixedBanner();

        drawData();
    };

    function drawBanner() {
        var $table_body = $('.ivu-table-body');
        var $table = $table_body.find('table');
        $table.before('' + '<div id="imgWindow" style="width:' + ($table_body.width() - 17) + 'px;height:' + ($table_body.height() - 15) + 'px">' + '   <div id="imgBanner" style="width:' + $table.width() + 'px;height:' + $table.height() + 'px"></div>' + '</div>');
        var positionTop = $('#imgWindow').offset().top;  // 创建的这个div，相对于外层窗口的top
        // 根据滚动条，同步滚动
        $table_body.scroll(function () {
            setTimeout(function () {
                $("#imgBanner").offset({
                    left: -1 * $table_body.scrollLeft(),
                    top: -1 * $table_body.scrollTop() + positionTop
                });
            }, 10);
        });

        $("#imgBanner").mousewheel(function (event, delta) {
            setTimeout(function () {

                if (delta > 0) {
                    $table_body.scrollTop($table_body.scrollTop() - 160);
                } else {
                    $table_body.scrollTop($table_body.scrollTop() + 160);
                }
            }, 50);

            return false;
        });
    }

    function drawFixedBanner() {
        // let $table_body = $('.ivu-table-body');
        var $table_body_fixed = $('.ivu-table-fixed-body');
        var $table = $table_body_fixed.find('table');

        $table.before('' + '<div id="imgWindow_Fixed" style="width:' + $table_body_fixed.width() + 'px;height:' + $table.height() + 'px">' + '   <div id="imgBanner_Fixed" style="width:' + $table_body_fixed.width() + 'px;height:' + $table.height() + 'px"></div>' + '</div>');
    }

    function drawData() {
        var addHtml = '',
            addFixedHtml = '';
        var areaObj = null;
        g_allData.forEach(function (q) {
            // 确定当前列数据应该显示在冻结列，还是普通列
            areaObj = g_areaArr.find(function (o) {
                return o.name === q.name;
            });
            if (areaObj) {
                if (areaObj.fixed) {
                    addFixedHtml += drawInFixedCol(q);
                } else {
                    addHtml += drawInCol(q);
                }
            }
        });
        $('#imgBanner_Fixed').append(addFixedHtml);
        $('#imgBanner').append(addHtml);
    }

    function drawInFixedCol(colData) {
        var $col = $('div.ivu-table-fixed-header span:contains("' + colData.name + '")'); // 找到当前列
        if ($col.length > 0) {
            $col = $col.parent().parent(); // 获得该span所在的th
            return getDrawHtml($col, colData);
        }
        return '';
    }

    function drawInCol(colData) {
        var $col = $('div.ivu-table-header span:contains("' + colData.name + '")'); // 找到当前列
        if ($col.length > 0) {
            $col = $col.parent().parent(); // 获得该span所在的th
            return getDrawHtml($col, colData);
        }
        return '';
    }

    function getDrawHtml($col, colData) {
        var addHtml = '';
        colData.data.forEach(function (q) {
            // 获得图形的横坐标
            var x_start = $col.offset().left;

            // 获得图形的开始y位置
            var y_start = getRowStartPosition(q.endDate);

            // 获得图形的结束y位置
            var y_end = getRowEndPosition(q.beginDate);

            var imgObj = DiyImg[q.type];

            switch (imgObj.type) {
                case 'rect':
                    addHtml += getRectHtml($col, x_start, y_start, y_end, imgObj, q);
                    break;
                case 'image':
                    addHtml += getImageHtml($col, x_start, y_start, y_end, imgObj, q);
                    break;
                case 'line':
                    addHtml += getLineHtml($col, x_start, y_start, y_end, imgObj, q);
                    break;
                case 'arrow':
                    // 箭头
                    addHtml += getArrowHtml($col, x_start, y_start, y_end, imgObj, q);
                    break;
                case 'banner':
                    // 大面积色块
                    addHtml += getBannerHtml($col, x_start, y_start, y_end, imgObj, q);
                    break;
            }
        });

        return addHtml;
    }

    //REVIEW 这个算法有优化的空间
    function getRowPosition(date) {
        return (g_dateArr.indexOf(date.pattern('yyyy年MM月')) + 1) * g_rowHeight; // 加1是为了把位置定位在这一行的下边线上
    }

    function getRowStartPosition(date) {
        return getRowPosition(date) - g_rowHeight;
    }

    function getRowEndPosition(date) {
        return getRowPosition(date);
    }

    // 创建矩形的dom
    function getRectHtml($col, p_x_start, p_y_start, p_y_end, p_imgObj, p_data) {
        var m_height = p_y_end - p_y_start;

        var newDOM = createDiv(p_imgObj, p_data);
        newDOM.addClass('diy-chart diy-' + p_imgObj.type + ' diy-size-' + p_imgObj.size);
        newDOM.css('left', p_x_start + ($col.width() - p_imgObj.size * g_sizeWidth) / 2 + (p_data.addRight ? p_data.addRight : 0) - (p_data.addLeft ? p_data.addLeft : 0)) // 这个20是我定义的每1个size的递增宽度，这里是为了居中显示图案
            .css('top', p_y_start).css('height', m_height).css('z-index', p_data.zIndex);
        if (p_imgObj.color || p_data.color) {
            // 如果数据带了颜色，则优先用数据的颜色
            newDOM.css('background-color', p_data.color ? p_data.color : p_imgObj.color);
        } else if (p_imgObj.color_linear_gradient) {
            newDOM.css('background-image', p_imgObj.color_linear_gradient);
        } else if (p_imgObj.src) {
            newDOM.css('background-image', 'url(' + p_imgObj.src + ')');
        }

        if (p_imgObj.border) {
            newDOM.css('border', p_imgObj.border);
        }

        if (p_data.text) {
            newDOM.html('<div class="diy-chart-text">' + p_data.text + '</div>');
        }
        return newDOM.get(0).outerHTML;
    }

    // 创建图片的dom
    function getImageHtml($col, p_x_start, p_y_start, p_y_end, p_imgObj, p_data) {
        var m_height = p_y_end - p_y_start;

        var newDOM = createDiv(p_imgObj, p_data);
        newDOM.addClass('diy-chart diy-' + p_imgObj.type + ' diy-size-' + p_imgObj.size);
        newDOM.css('left', p_x_start + $col.width() / 4).css('top', p_y_start).css('height', m_height).css('z-index', p_data.zIndex);
        if (p_imgObj.borderColor) {
            newDOM.css('border', '1px solid ' + p_imgObj.borderColor);
        }
        if (p_imgObj.src) {
            newDOM.css('background-image', 'url(' + p_imgObj.src + ')');
        }
        return newDOM.get(0).outerHTML;
    }

    // 创建线条的dom
    function getLineHtml($col, x_start, y_start, y_end, p_imgObj, p_data) {

        // 获得终点所在的列
        var $toCol = $col.parent().find('span:contains("' + p_data.to + '")');
        if ($toCol.length === 1) {
            $toCol = $toCol.parent().parent();

            var x_end = $toCol.offset().left;

            var isToUp = y_end - y_start > 0;
            var isToRight = x_end - x_start > 0;
            var m_height = Math.abs(y_end - y_start);
            var m_width = getWidth();
            var realWidth = getRealWidth(); // 计算出真正的长度，因为div被旋转了，实际长度比宽度要长
            var transformOrigin = getTransformOrigin();
            var transformRotate = (transformOrigin === 0 ? 1 : -1) * getTanDeg(m_height / m_width);
            var m_left = getLeft(); // 因为斜边比实际的宽度长，所以需要稍微平移一下

            var newDOM = createDiv(p_imgObj, p_data);
            newDOM.addClass('diy-chart diy-' + p_imgObj.type);
            newDOM.css('left', m_left).css('top', y_start).css('width', realWidth).css('transform-origin', transformOrigin).css('transform', 'rotate(' + transformRotate + 'deg)');
            if (p_imgObj.color) {
                newDOM.css('background-color', p_imgObj.color);
            } else if (p_imgObj.src) {
                newDOM.css('background-image', 'url(' + p_imgObj.src + ')');
            }
            return newDOM.get(0).outerHTML;
        }

        return '';

        function getWidth() {
            if (isToRight) {
                return x_end - x_start + $toCol.width();
            } else {
                return x_start - x_end + $col.width();
            }
        }

        function getTanDeg(valu) {
            return Math.atan(valu) * 180 / Math.PI;
        }

        // 获得斜边长度
        function getRealWidth() {
            return Math.sqrt(Math.pow(m_width, 2) + Math.pow(m_height, 2));
        }

        // 箭头和线段不一样，不需要贯穿当前列
        function getLeft() {
            if (isToRight) {
                return x_start - (realWidth - m_width);
            } else {
                return x_end;
            }
        }

        // 计算旋转中心点位置，在左边还是右边
        function getTransformOrigin() {
            if (isToRight) {
                if (isToUp) {
                    return realWidth;
                } else {
                    return 0;
                }
            } else {
                if (isToUp) {
                    return 0;
                } else {
                    return realWidth;
                }
            }
        }
    }

    // 创建箭头的dom
    function getArrowHtml($col, x_start, y_start, y_end, p_imgObj, p_data) {

        // 获得终点所在的列
        var $toCol = $col.parent().find('span:contains("' + p_data.to + '")');
        if ($toCol.length === 1) {
            $toCol = $toCol.parent().parent();

            var x_end = $toCol.offset().left;

            var isToUp = y_end - y_start > 0;
            var isToRight = x_end - x_start > 0;
            var m_height = Math.abs(y_end - y_start);
            var m_width = getWidth();
            var realWidth = getRealWidth(m_width, m_height); // 计算出真正的长度，因为div被旋转了，实际长度比宽度要长
            var transformOrigin = getTransformOrigin(isToUp, isToRight, realWidth);
            var transformRotate = (transformOrigin === 0 ? 1 : -1) * getTanDeg(m_height / m_width);
            var m_left = getLeft(); // 因为斜边比实际的宽度长，所以需要稍微平移一下

            var newDOM = createDiv(p_imgObj, p_data);
            newDOM.addClass('diy-chart diy-' + p_imgObj.type);
            newDOM.css('left', m_left).css('top', y_start).css('width', realWidth).css('transform-origin', transformOrigin) // 如果方向是往左，则以
                .css('transform', 'rotate(' + transformRotate + 'deg)');
            // if (p_imgObj.color) {
            //     newDOM.css('background-color', p_imgObj.color);
            // }
            // else if (p_imgObj.src) {
            //     newDOM.css('background-image', 'url(' + p_imgObj.src + ')');
            // }

            newDOM.append('<div class="diy-arrow-tou diy-arrow-tou-' + (transformOrigin === 0 ? "left" : "right") + '" style="border-' + (transformOrigin === 0 ? "right" : "left") + '-color:' + p_imgObj.color + '"></div>');
            if (p_imgObj.move && p_imgObj.move === 1) {
                newDOM.append('<div>' + '<div class="diy-arrow-xu" style="border:1px dashed ' + p_imgObj.color + '"></div>' + '</div>');
            } else {
                newDOM.append('<div>' + '<div class="diy-arrow-xi" style="background-color:' + p_imgObj.color + '"></div>' + '<div class="diy-arrow-cu" style="background-color:' + p_imgObj.color + '"></div>' + '<div class="diy-arrow-xi" style="background-color:' + p_imgObj.color + '"></div>' + '</div>');
                newDOM.append('<div class="diy-arrow-wei diy-arrow-wei-' + (transformOrigin === 0 ? "right" : "left") + '" style="background-color:' + p_imgObj.color + '"></div>');
                newDOM.append(createText());
            }

            return newDOM.get(0).outerHTML;
        }

        return '';

        // 获得宽度，因为方向的不同，会导致起点的位置和终点的位置在当前列靠左的位置，或者靠右的位置
        function getWidth() {
            if (isToRight) {
                return x_end - x_start;
            } else {
                return x_start - x_end;
            }
        }

        // 箭头和线段不一样，不需要贯穿当前列
        function getLeft() {
            if (isToRight) {
                return x_start - (realWidth - m_width);
            } else {
                return x_end;
            }
        }

        function createText() {
            //REVIEW 比较复杂，先随便找个位置显示
            return '<div style="position: absolute;top:15px;left:50%;transform:rotate(' + -1 * transformRotate + 'deg)">' + p_data.text + '</div>';
        }
    }

    // 创建色块的dom
    function getBannerHtml($col, p_x_start, p_y_start, p_y_end, p_imgObj, p_data) {
        var m_height = p_y_end - p_y_start - 3;

        var newDOM = createDiv(p_imgObj, p_data);
        newDOM.addClass('diy-chart diy-' + p_imgObj.type);
        newDOM.css('left', p_x_start).css('width', $col.width() + 1); // 加1是为了遮挡表格表框
        if (p_imgObj.size) {
            var tempHeight = p_imgObj.size * 10;
            newDOM.css('top', p_y_start + (m_height / 2 - tempHeight / 2)).css('height', tempHeight);
        } else {
            newDOM.css('top', p_y_start).css('height', m_height);
        }

        if (p_imgObj.borderColor) {
            newDOM.css('border-top', '1px solid ' + p_imgObj.borderColor);
            newDOM.css('border-bottom', '1px solid ' + p_imgObj.borderColor);
        }
        if (p_imgObj.color || p_data.color) {
            newDOM.css('background-color', p_imgObj.color || p_data.color);
        } else if (p_imgObj.color_linear_gradient) {
        } else if (p_imgObj.src) {
            newDOM.css('background-image', 'url(' + p_imgObj.src + ')');
        }
        return newDOM.get(0).outerHTML;
    }

    function getTanDeg(valu) {
        return Math.atan(valu) * 180 / Math.PI;
    }

    // 获得斜边长度
    function getRealWidth(p_width, p_height) {
        return Math.sqrt(Math.pow(p_width, 2) + Math.pow(p_height, 2));
    }

    // 计算旋转中心点位置，在左边还是右边
    function getTransformOrigin(p_isToUp, p_isToRight, p_width) {
        if (p_isToRight) {
            if (p_isToUp) {
                return p_width;
            } else {
                return 0;
            }
        } else {
            if (p_isToUp) {
                return 0;
            } else {
                return p_width;
            }
        }
    }

    function createDiv(p_imgObj, p_data) {
        var $dom = $('<div/>');
        if (p_imgObj) {
            $dom.attr('data-cn', p_imgObj.cn);
        }
        if (p_data.beginDate) {
            $dom.attr('data-begin-date', p_data.beginDate.pattern('yyyy/MM/dd'));
        }
        if (p_data.endDate) {
            $dom.attr('data-end-date', p_data.endDate.pattern('yyyy/MM/dd'));
        }
        if (p_data.text) {
            $dom.attr('data-text', p_data.text);
        }
        return $dom;
    }

    window.DiyDraw = {
        draw: draw
    };
})();